// Clase Calendar.

var Calendar_Instances = [];
var modalLayer;

function Calendar(id)
{
    // Propiedades
    this.id = id;

    this.monthNames = [];
    this.dayNames = [];
    
    this.cssClass = "";
    this.year = 0;
    this.month = 0;    
    this.day = 0;    
    
    this.focuseable = true;
    this.parentID = "";
    this.validDate = false;
    this.isWritten = false;
                
    // Public Functions
    this.show = Calendar_Show;
    this.clone = Calendar_Clone;    
    this.draw  = Calendar_Draw;
    this.redraw  = Calendar_Redraw;
    this.getDate = Calendar_GetDate;   
    this.setDate = Calendar_SetDate;    
    this.emptyDate = Calendar_EmptyDate;    
        
    // Private Functions
    this.drawTitle = Calendar_DrawTitle;
    this.redrawTitle = Calendar_RedrawTitle;
    this.drawHeader = Calendar_DrawHeader;
    this.drawDays = Calendar_DrawDays;
    this.getDaysInMonth = Calendar_GetDaysInMonth;
    this.getFocusFunction = Calendar_GetFocusFunction;
    this.getTitleHTML = Calendar_GetTitleHTML;    
    
    // Envents 
    this.onDayChange = "";
    
    Calendar_Instances[id] = this;
}


// -----------------------------------------------------------------------------------------------------------------
// Public Functions
// -----------------------------------------------------------------------------------------------------------------

function Calendar_Clone(newId)
{
    var newCalendar = new Calendar(newId);

	newCalendar.monthNames = this.monthNames.slice();
	newCalendar.dayNames = this.dayNames.slice();
	newCalendar.cssClass = this.cssClass;
	
	newCalendar.year = this.year;
    newCalendar.month = this.month;
    newCalendar.day = this.day;
    
    return newCalendar;
}

function Calendar_Show(container)
{
    var divcont = document.createElement("div");
    divcont.id = "divcont" + this.id;

    var outerTable = document.createElement("table");
    outerTable.id = this.id;
    outerTable.className = this.cssClass;
    divcont.appendChild(outerTable);
    
    // Titulo
    var trTitle = outerTable.insertRow(outerTable.rows.length);
    var tdTitle = trTitle.insertCell(trTitle.cells.length);
    
    this.drawTitle(tdTitle);
    
    // Contenido
    var trMainTable = outerTable.insertRow(outerTable.rows.length);
    var tdMainTable = trMainTable.insertCell(trMainTable.cells.length);

    var mainTable = document.createElement("table");
    mainTable.id = "mainTable_" + this.id;
    tdMainTable.appendChild(mainTable);
    
    this.draw(mainTable);
    
    if(container)
        container.appendChild(divcont);
    else
        return "<div id=\"divcont" + this.id + "\">" + divcont.innerHTML + "</div>";
}

function Calendar_Redraw()
{
    var table = document.getElementById("mainTable_" + this.id);
    this.draw(table);
    this.redrawTitle();    
}

function Calendar_Draw(table)
{
    // Limpio la tabla
    var count = table.rows.length;
    for(var i=0; i<count; i++)
        table.deleteRow(0);

    this.drawHeader(table);
    this.drawDays(table);
    
    this.isWritten = true;
}

function Calendar_GetDate()
{
    return ({year:this.year, month:this.month, day:this.day});
}

function Calendar_SetDate(date)
{
    this.year = date.year;
    this.month = date.month;
    this.day = date.day;  
    this.validDate = true;
    
    if(this.isWritten)
        this.redraw();
}

function Calendar_EmptyDate()
{
    this.day = 0;  
    this.validDate = false;
    
    if(this.isWritten)
        this.redraw();    
}

// -----------------------------------------------------------------------------------------------------------------
// Private Functions
// -----------------------------------------------------------------------------------------------------------------

function Calendar_DrawTitle(container)
{
    var table = document.createElement("table");
    table.style.width = "100%";
    table.setAttribute("calendar", "yes");
    
    var row = table.insertRow(table.rows.length);
    var cellPreviousMonth = row.insertCell(row.cells.length);
    var cellTitle = row.insertCell(row.cells.length);
    var cellNextMonth = row.insertCell(row.cells.length);

    // Previous Month    
    cellPreviousMonth.setAttribute("align", "left");
    cellPreviousMonth.innerHTML = "<A calendar=\"yes\" href=\"javascript:" + this.getFocusFunction() + "Calendar_PreviousMonth(\'" + this.id + "\')\"> < <\A>";
    
    // Title
    cellTitle.id = "title_" + this.id;
    Common.setStyleAttribute(cellTitle, "text-align", "center");
    cellTitle.innerHTML = this.getTitleHTML();
    
    // Next Month
    cellNextMonth.setAttribute("align", "right");
    cellNextMonth.innerHTML = "<A calendar=\"yes\" href=\"javascript:" + this.getFocusFunction() + "Calendar_NextMonth(\'" + this.id + "\')\"> > <\A>";
    
    container.appendChild(table);
}

function Calendar_RedrawTitle()
{
    var td = document.getElementById("title_" + this.id)
    td.innerHTML = this.getTitleHTML();
}

function Calendar_DrawHeader(table)
{
    var row = table.insertRow(table.rows.length);
    
    for (var weekday = 0; weekday < 7; weekday++)
    {
        var cell = row.insertCell(row.cells.length);
        cell.className = "header";
        cell.innerHTML = this.dayNames[weekday];
    }    
}

function Calendar_DrawDays(table)
{
    var days = this.getDaysInMonth(this.year, this.month);
    var firstDay = new Date(this.year, this.month-1, 1);
    var dayOfWeek = firstDay.getDay();
            
    var day = 1;

    while(day <= days)
    {
        var row = table.insertRow(table.rows.length);

        for (var weekDay = 0; weekDay < 7; weekDay++)
        {
            var cell = row.insertCell(row.cells.length);
            
            if(day == this.day)
                cell.className = "selectedDay";
            else
                cell.className = "day";

            if ((dayOfWeek == weekDay) && (day <= days)) {
                cell.id = "day_" + day + "_" + this.id;
                cell.innerHTML = "<a calendar=\"yes\" href=\"javascript:" + this.getFocusFunction() + "Calendar_DayChange('" + this.id + "', " + day + ")\">" + day + "</a>";        

                day++;
                dayOfWeek = (dayOfWeek + 1) % 7;
            }
            else {
                cell.innerHTML = "&nbsp;";                    
            }
        }
    }
}

function Calendar_GetDaysInMonth(year, month)
{
    return 32 - new Date(year, month-1, 32).getDate();
}
        
function Calendar_GetFocusFunction()
{
    if (this.Focuseable)
        return "FocusManager.setFocus(\'" + this.id + "\');";
    else
        return "";  
}

function Calendar_GetTitleHTML()
{
    var titleHTML = "<table align = \"center\"><tr>";
    titleHTML += "<td class=\"monthLabel\">" + this.monthNames[this.month-1] + "</td>";
    titleHTML += "<td><input calendar=\"yes\" id=\"year_" + this.id + "\" value=\"" + this.year + "\" onfocusout=\"Calendar_UpdateYear('" + this.id + "')\" onkeyup=\"Calendar_OnYearKeyUp(\'" + this.id + "\', event)\" class=\"yearInput\" maxlength=\"4\" type=\"text\" autocomplete=\"off\"></td>";
    titleHTML += "</tr></table>";
    
    return titleHTML;
}
        
        
// ------------------------------------------------------------------------------------------------------
// Funciones externas.
// ------------------------------------------------------------------------------------------------------

function Calendar_Get(id)
{
    return Calendar_Instances[id];
}

function Calendar_PreviousMonth(id)  
{
    var calendar = Calendar_Get(id);
    
    if(calendar.month==1) {
        calendar.year--;
        calendar.month = 12;
    }
    else {
        calendar.month--;
    }
    
    calendar.day = 0;
    
    calendar.redraw();
}

function Calendar_NextMonth(id)
{
    var calendar = Calendar_Get(id);
    
    if(calendar.month==12) {
        calendar.year++;
        calendar.month = 1;
    }
    else {
        calendar.month++;
    }    
    
    calendar.day = 0;
    
    calendar.redraw();
}

function Calendar_DayChange(id, day)
{
    var calendar = Calendar_Get(id);
    var dayCell;
    
    if(calendar.day != 0) {
        dayCell = document.getElementById("day_" + calendar.day + "_" + calendar.id);
        dayCell.className = "day"
    }

    dayCell = document.getElementById("day_" + day + "_" + calendar.id);
    dayCell.className = "selectedDay"
    
    calendar.day = day;
    
    if(calendar.onDayChange)
        eval(calendar.onDayChange + "(" + calendar.year + "," + calendar.month + "," + calendar.day + ")");
    
    if(calendar.parentID)
        DatePicker_RefreshValue(calendar.parentID, calendar.year, calendar.month, calendar.day);
    
    this.validDate = true;  
}

function Calendar_OnYearKeyUp(id, ev)
{
    var ev = ev || window.event;
    
    if(ev.keyCode==13) { // Enter
        Calendar_UpdateYear(id);
    }
}

function Calendar_UpdateYear(id)
{
    var calendar = Calendar_Get(id);
    var strYear = document.getElementById("year_" + id).value;
    
    calendar.year = parseInt(strYear, 10);
    calendar.redraw();    
}

function Calendar_Get(id)
{
    return Calendar_Instances[id];
}

// -----------------------------------------------------------------------------------------------------------------
// Funciones de foco
// -----------------------------------------------------------------------------------------------------------------

FocusManager.registerControl("Calendar_DisposeFocus");

function Calendar_DisposeFocus(id)
{
    // Por ahora si un calendario pierde el foco no hace nada
}
